package com.whenjun.service.core;

import cn.dev33.satoken.stp.StpUtil;
import com.ifootbook.util.EmptyUtil;
import com.ifootbook.util.FootBookException;
import com.ifootbook.util.MD5Util;
import com.ifootbook.util.Util;
import com.whenjun.common.Base;
import com.whenjun.common.LoggerParent;
import com.whenjun.dto.login.BaseLogin;
import com.whenjun.dto.login.LoginResp;
import com.whenjun.dto.login.TokenInfo;
import com.whenjun.entity.AccessLog;
import com.whenjun.entity.Account;
import com.whenjun.service.impl.AccessLogServiceImpl;
import com.whenjun.service.impl.AccountServiceImpl;
import com.whenjun.util.SaTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

@Service
public class LoginService extends LoggerParent {

    @Autowired
    private Base base;

    @Autowired
    private AccountServiceImpl accountService;

    @Autowired
    private AccessLogServiceImpl accessLogService;


    @Transactional
    public TokenInfo login(BaseLogin baseLogin) {
        TokenInfo tokenInfo = new TokenInfo();

        Account account = accountService.selectByName(baseLogin.getUsername());
        if (account == null) {
            // 工号
            account = accountService.selectByJobNo(baseLogin.getUsername());
            if (account == null) {
                throw new FootBookException("用户名或密码错误");
            }
        }
        if(account.getStatus()) {
            throw new FootBookException("该账户已被注销");
        }
        String md5Pass = MD5Util.getMD5(baseLogin.getPassword());
        if(!md5Pass.equals(account.getPassword())) {
            throw new FootBookException("用户名或密码错误");
        }
        StpUtil.login(account.getId());
        String token = StpUtil.getTokenValue();
        tokenInfo.setToken(token);
        tokenInfo.setExpire(base.SA_TOKEN_TIMEOUT);
        accessLogService.addLog("登录系统");
        return tokenInfo;
    }



    @Transactional
    public LoginResp userInfo() {

        String userId = SaTokenUtil.getUserId();
        Account account = accountService.getById(userId);
        LoginResp loginResp = new LoginResp();

        loginResp.setId(account.getId());
        loginResp.setUpdatePass(account.getUpdatePass()==null ? false : !account.getUpdatePass());
        loginResp.setJobNo(account.getJobNo());
        loginResp.setUsername(account.getUsername());

        // 当前用户角色
        loginResp.setRole(EmptyUtil.isEmpty(account.getType()) ? "member" : account.getType());

        return loginResp;
    }

    @Transactional
    public void logout(HttpServletRequest request) {
        StpUtil.logout();
        accessLogService.addLog("登出系统");
    }
}
